package com.jichaoyun.controller;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;

import java.util.List;
import javax.annotation.Resource;

import com.jichaoyun.common.enums.MyExceptiontType;
import com.jichaoyun.common.ex.MyException;
import com.jichaoyun.common.model.Result;

import com.jichaoyun.dao.mapper.ScheduelObjectMapper;
import com.jichaoyun.dao.mapper.ScheduelRealtimeMapper;
import com.jichaoyun.model.entity.ScheduelRealtime;
import com.jichaoyun.model.vo.ScheduelObject;
import com.jichaoyun.model.vo.UserVo;
import com.jichaoyun.service.IUserService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/sys/scheduel")
public class RealTimeSchduelController {

    @Resource
    private ScheduelRealtimeMapper scheduelRealtimeMapper;

    @Resource
    private ScheduelObjectMapper scheduelObjectMapper;

    @Resource
    private IUserService userService;

    //获取聊天内容列表
    @GetMapping("/getScheduelList")
    public Result<List<ScheduelRealtime>> getScheduelList(@RequestParam("sendId") Integer sendId,
                                                          @RequestParam("receiveId")Integer receiveId){
        //获取最近的十条消息
        return Result.success(scheduelRealtimeMapper.getChatList(sendId,receiveId));
    }

    //获取实时调度指令对象和最近聊天记录
    @GetMapping("/userList")
    public Result<List<ScheduelObject>> getUserList(@RequestParam("searchText") String searchText, @RequestHeader("token") String token){
        //如果用户是管理员，则查最近一条是自己发的调度消息，如果是非管理员，则搜最近一条
        UserVo data = userService.getUserInfo(token);
        if(data == null){
            throw new MyException(MyExceptiontType.TOKENEXPIRED,null);
        }
        if(2==data.getUserRole()){
            if(searchText ==""){
                return Result.success(scheduelObjectMapper.getScheduelObjectListNonSearchText(data.getId()));
            }else{
                return Result.success(scheduelObjectMapper.getScheduelObjectList(searchText,
                    data.getId()));
            }
        }else{
            return Result.success(scheduelObjectMapper.getScheduelObjectSystem(data.getId()));
        }
    }

    @PostMapping("/readMsg")
    public Result<Void> readMsg(@RequestParam("sendId")Integer sendId,
        @RequestParam("receiveId")Integer receiveId){
        UpdateWrapper<ScheduelRealtime> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("send_id",sendId)
            .eq("receive_id",receiveId)
            .set("is_read",true);
        scheduelRealtimeMapper.update(null,updateWrapper);
        return Result.success();
    }
}
